package com.dap.dao.interceptor;

import com.dap.dao.SaveSqlLogFlag;
import com.dap.dao.mybatis.SaveSqlLogInterface;
import com.dap.param.CommonServiceContext;
import com.dap.utils.SpringUtils;
import com.dap.utils.StackTraceUtil;
import com.dap.utils.TraceIdUtils;
import org.apache.ibatis.mapping.BoundSql;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wangmin
 * @discription
 * @created 2020-05-08 10:14
 */
public abstract class SaveSqlLogUtil {
    private final static Logger logger = LoggerFactory.getLogger(SaveSqlLogUtil.class);

    private static String generateStackTraceStr() {
        StackTraceElement[] st = Thread.currentThread().getStackTrace();
        return StackTraceUtil.generateStackTraceStr(st, 20, "com.sbp.", false);
    }

    public static void saveSqlLog(BoundSql boundSql) {
        try {
            if (!SaveSqlLogFlag.getIsSaveSqlLog()) {
                return;
            }

            if (boundSql.getSql().startsWith("select ") || boundSql.getSql().startsWith("SELECT ")) {
                return;
            }

            if (CommonServiceContext.getIsFrontRequest() && null != CommonServiceContext.getCtrlData()) {
                SaveSqlLogInterface saveSqlLogInterface = SpringUtils.getBean(SaveSqlLogInterface.class);
                if (saveSqlLogInterface != null) {
                    String stackTrace = generateStackTraceStr();
                    saveSqlLogInterface.save(boundSql,
                                             CommonServiceContext.getCtrlData(),
                                             CommonServiceContext.getGroupName(),
                                             TraceIdUtils.getTraceId(),
                                             stackTrace);
                }
            }
        } catch (Exception e) {
            logger.warn("sql="+boundSql.getSql(), e);
        }
    }
}
